//
//  ZFBadgeStretchView.m
//  ZFBadgeView
//
//  Created by fyzq on 2021/9/7.
//

#import "ZFBadgeStretchView.h"
#define ZFWeakSelf __weak typeof(self) weakSelf = self
#define ZFStrongSelf __strong typeof(weakSelf) strongSelf = weakSelf;
@interface ZFBadgeStretchView()
@property(nonatomic,strong)UIView *circleView;
@property(nonatomic,strong)ZFBadgeControl *badgeControl;
@property (nonatomic, strong) CAShapeLayer *shapeLayer;

@property(nonatomic,assign)CGFloat circleR1;
@property(nonatomic)CGRect currentReact;

@property(nonatomic,assign)CGFloat distance;

@end
@implementation ZFBadgeStretchView

- (instancetype)init{
    self = [super init];
    if (self) {
        [self initZFBadgeStretchView];
    }
    return self;
}

-(void)initZFBadgeStretchView{
    _position = CGPointMake(5, 5);
    _canDrag = NO;
    _maxDragDistance = 80;
    _canLoogPress = NO;
    self.bgColor = UIColor.redColor;
    [self addSubview:self.circleView];
    [self addSubview: self.badgeControl];

    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[badgeControl]-0-|" options:0 metrics:0 views:@{@"badgeControl":self.badgeControl}]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[badgeControl]-0-|" options:0 metrics:0 views:@{@"badgeControl":self.badgeControl}]];
    
}



- (void)layoutSubviews{
    [super layoutSubviews];
    if (![NSStringFromCGRect(self.frame)isEqualToString:NSStringFromCGRect(self.currentReact)]) {
        [self layoutCircle];
        self.badgeControl.layer.cornerRadius = [self miniSize]/2;
        self.circleR1 =  [self miniSize] / 2.0;
        self.currentReact  = self.frame;
       
    }
}

-(void)layoutCircle{
    self.circleView.hidden = false;
    CGFloat x = (CGRectGetWidth(self.frame) - [self miniSize])/2;
    CGFloat y = (CGRectGetHeight(self.frame) - [self miniSize])/2;
    self.circleView.frame = CGRectMake(x, y, [self miniSize], [self miniSize]);
    self.circleView.layer.cornerRadius = [self miniSize]/2;
}


#pragma mark --- setter
- (void)setText:(NSString *)text{
    if (_text !=text) {
        _text = text;
        self.badgeControl.titleLabel.text = text;
    }
}
-(void)setTextColor:(UIColor *)textColor{
    if (_textColor != textColor) {
        _textColor = textColor;
        self.badgeControl.titleLabel.textColor = textColor;
    }
}

- (void)setFont:(UIFont *)font{
    if (_font !=font) {
        _font = font;
        self.badgeControl.titleLabel.font = font;
    }
}
- (void)setImage:(UIImage *)image{
    _image = image;
    self.badgeControl.image = image;
}
- (void)setEdgeInsets:(UIEdgeInsets)edgeInsets{
    _edgeInsets = edgeInsets;
    self.badgeControl.edgeInsets = edgeInsets;
}
- (void)setBgColor:(UIColor *)bgColor{
    _bgColor = bgColor;
    self.badgeControl.bgColor = bgColor;
    self.badgeControl.backgroundColor = self.bgColor;
    self.circleView.backgroundColor = self.bgColor;
}
#pragma mark --- getter
-(CGFloat)miniSize{
    return  MIN(CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
}

- (ZFBadgeControl *)badgeControl{
    if (!_badgeControl) {
        _badgeControl = [ZFBadgeControl new];
        _badgeControl.titleLabel.font = [UIFont systemFontOfSize:10];
        _badgeControl.layer.masksToBounds = YES;
        _badgeControl.translatesAutoresizingMaskIntoConstraints = NO;
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];///添加手势
        [_badgeControl addGestureRecognizer:pan];
        UILongPressGestureRecognizer *loog = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(loonAction:)];
        [_badgeControl addGestureRecognizer:loog];
        
    }
    return _badgeControl;
}


- (UIView *)circleView{
    if (!_circleView) {
        _circleView =  [UIView new];
        _circleView.layer.masksToBounds = YES;
        _circleView.translatesAutoresizingMaskIntoConstraints = NO;
    }
    return _circleView;
}

- (CAShapeLayer *)shapeLayer{
    if (!_shapeLayer) {
        _shapeLayer = [CAShapeLayer layer];
        _shapeLayer.fillColor = self.backgroundColor.CGColor;
    }
    return  _shapeLayer;
}

///移除layer
-(void)removeLayer{
    [self.shapeLayer removeFromSuperlayer];
    self.circleView.hidden =YES;
    self.shapeLayer = nil;
}
#pragma mark --- 销毁动画
-(void)removeAnimation{
    [self animation];
}

#pragma mark --- s手势
////长按手势
-(void)loonAction:(UILongPressGestureRecognizer*)loog{
    if (!self.canLoogPress) {
        return;
    }
    if (loog.state == UIGestureRecognizerStateBegan) {
        [self removeAnimation];
    }
}
////拖动手势
-(void)pan:(UIPanGestureRecognizer *)pan{
 
    ///是否可以被拖动
    if (!self.canDrag) {
        return;
    }
    if (pan.state == UIGestureRecognizerStateChanged) {
        CGPoint point = [pan locationInView:self];
        self.badgeControl.center = point;
        
        ////获取两个圆心距离
        CGPoint center1 = self.circleView.center;
        CGPoint center2 = self.badgeControl.center;
        CGFloat distance = sqrtf(pow(center2.x - center1.x, 2) + pow(center2.y - center1.y, 2));
        self.distance = distance;
    
        ////超出最大距离移除layer 隐藏小圆
        if (self.distance > self.maxDragDistance) {
            [self removeLayer];
        }else{
            self.circleView.hidden =NO;
            [self drawShapeLayer:center1 r2center:center2];
        }
    }else if (pan.state == UIGestureRecognizerStateCancelled ||pan.state == UIGestureRecognizerStateFailed ||pan.state == UIGestureRecognizerStateEnded){
        [self removeLayer];
        ////如果松手了超出最大距离 销毁
        if(self.distance >self.maxDragDistance){
            [self removeAnimation];
            return;
        }
        self.badgeControl.transform = CGAffineTransformIdentity;
        ZFWeakSelf;
        [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.8 options:UIViewAnimationOptionOverrideInheritedCurve animations:^{
            ZFStrongSelf;
            strongSelf.badgeControl.center = strongSelf.circleView.center;
        } completion:^(BOOL finished) {
            ZFStrongSelf;
            [strongSelf layoutCircle];
        }];
    }
}

-(void)drawShapeLayer:(CGPoint)center1 r2center:(CGPoint)center2{
    if (self.circleView.hidden) {
        return;
    }
 
    CGFloat distance = self.distance;
    ///计算sinα、cosα
    CGFloat sinα = (center2.x - center1.x) / distance;
    CGFloat cosα = (center1.y - center2.y) / distance;
    self.badgeControl.transform = CGAffineTransformMakeRotation(sinα>0?acos(cosα):-acos(cosα));
    
    
     /// 计算圆1半径，逐渐变小。
    CGFloat r1 = [self miniSize] / 2.0 - (distance/20.0);
    /// 计算圆2半径，固定不变。
    CGFloat r2 = MAX(CGRectGetWidth(self.frame), CGRectGetHeight(self.frame)) / 2.0;
    /// 记录圆1半径
    self.circleR1 = r1;
    CGPoint pointA = CGPointMake(center1.x - r1 * cosα, center1.y - r1 * sinα);
    CGPoint pointB = CGPointMake(center1.x + r1 * cosα,  center1.y + r1 * sinα);
    CGPoint pointC = CGPointMake(center2.x + r2 * cosα, center2.y + r2 * sinα);
    CGPoint pointD = CGPointMake(center2.x - r2 * cosα, center2.y - r2 * sinα);
    CGPoint pointE = CGPointMake(pointA.x + distance / 2.0 * sinα, pointA.y - distance / 2.0 * cosα);
    CGPoint pointF = CGPointMake(pointB.x + distance / 2.0 * sinα, pointB.y - distance / 2.0 * cosα);

    /// 绘制贝塞尔曲线
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:pointA];
    [path addLineToPoint:pointB];
    [path addQuadCurveToPoint:pointC controlPoint:pointF];
    [path addLineToPoint:pointD];
    [path addQuadCurveToPoint:pointA controlPoint:pointE];


    /// 绘制图层并填充颜色
    self.shapeLayer.path = path.CGPath;
    self.shapeLayer.fillColor = self.bgColor.CGColor;
    [self.layer insertSublayer:self.shapeLayer below:self.badgeControl.layer];

    /// 修改圆1的尺寸
    self.circleView.bounds = CGRectMake(0, 0, r1*2, r1*2);
    self.circleView.center = center1;
    self.circleView.layer.cornerRadius = r1;
}


-(void)animation{
    self.badgeControl.hidden = YES;
    self.circleView.hidden = YES;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"images" ofType:@"bundle"];
    NSMutableArray *images = [NSMutableArray array];
    for (int i=0; i<5; i++) {
        NSString *imageName = [path stringByAppendingFormat:@"/ic_bomb_%d",i+1];
        [images addObject:[UIImage imageNamed:imageName]];
    }
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.badgeControl.frame];
    imageView.animationImages = images;
    [self insertSubview:imageView aboveSubview:self.badgeControl];
    
    imageView.animationDuration = 0.5;
    imageView.animationRepeatCount = 1;
    [imageView startAnimating];
    ZFWeakSelf;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        ZFStrongSelf;
        [strongSelf removeFromSuperview];
        if (strongSelf.completeBlock) {
            strongSelf.completeBlock();
        }
    });
}


@end



@interface ZFBadgeControl ()

@property(nonatomic,strong)UILabel *titleLabel;
@property(nonatomic,strong)UIImageView *imageView;
@property(nonatomic,copy)NSMutableArray  *items;

@end

@implementation ZFBadgeControl

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initZFBadgeControl];
    }
    return self;
}

-(void)initZFBadgeControl{
    self.layer.masksToBounds = YES;
    self.bgColor = UIColor.redColor;
   
    _edgeInsets = UIEdgeInsetsMake(0, 5, 0, 5);
 
    [self addSubview:self.imageView];
    [self addSubview:self.titleLabel];

    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[imageView]-0-|" options:0 metrics:0 views:@{@"imageView":self.imageView}]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[imageView]-0-|" options:0 metrics:0 views:@{@"imageView":self.imageView}]];
    [self layoutConstraint];
}

-(void)reloadData{
    [self setNeedsLayout];
}

#pragma mark --- 布局
-(void)layoutConstraint{
    [self removeConstraints:self.items];
    [self.items removeAllObjects];
    [self.items addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-left-[titleLabel]-right-|" options:0 metrics:@{@"left":@(_edgeInsets.left),@"right":@(_edgeInsets.right)} views:@{@"titleLabel":self.titleLabel}]];
    [self.items addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-top-[titleLabel]-bottom-|" options:0 metrics:@{@"top":@(_edgeInsets.top),@"bottom":@(_edgeInsets.bottom)} views:@{@"titleLabel":self.titleLabel}]];
    [self addConstraints:self.items];
}

#pragma mark --- setter
- (void)setImage:(UIImage *)image{
    if (_image !=image) {
        _image = image;
        self.imageView.image = image;
        self.backgroundColor = [UIColor clearColor];
    }
}
- (void)setBgColor:(UIColor *)bgColor{
    if (_bgColor !=bgColor) {
        _bgColor = bgColor;
        self.backgroundColor = bgColor;
    }
}

- (void)setEdgeInsets:(UIEdgeInsets)edgeInsets{
    if (![NSStringFromUIEdgeInsets(_edgeInsets) isEqualToString:NSStringFromUIEdgeInsets(edgeInsets)]) {
        _edgeInsets = edgeInsets;
        [self layoutConstraint];
    }
}


#pragma mark --- getter
- (UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [UILabel new];
        _titleLabel.font = [UIFont systemFontOfSize:8];
        _titleLabel.textColor = [UIColor whiteColor];
        _titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    }
    return _titleLabel;
}

- (UIImageView *)imageView{
    if (!_imageView) {
        _imageView = [UIImageView new];
        _imageView.translatesAutoresizingMaskIntoConstraints = NO;
    }
    return _imageView;
}

- (NSMutableArray *)items{
    if (!_items) {
        _items = [NSMutableArray array];
    }
    return _items;
}


@end
